﻿using System;
using Landpy.CruiseControlNet.ConfigurationSidekick.Resources;
using Landpy.CruiseControlNet.FacadeInterface.ConfigurationModule;

namespace Landpy.CruiseControlNet.ConfigurationSidekick.ConfigTreeModule
{
    class RolePermissionUserHandler : UpdateChildrenNode
    {
        public override void UpdateChildrenNodes(ChildrenNodeContext childrenNodeContext)
        {
            var treeNodeIndentity = this.GetTreeNodeIndentity(childrenNodeContext);
            var treeNodesBuilder = this.GetTreeNodesBuilder(childrenNodeContext.CruiseControl);
            if (treeNodeIndentity.Type == TreeNodeType.InternalRolePermission)
            {
                if (childrenNodeContext.ChangedValueKey == typeof(UserName).Name)
                {
                    var securityUsersTreeNode = childrenNodeContext.SelectedNode.Nodes[Resource.TreeNode_SecurityUsers];
                    securityUsersTreeNode.Remove();
                    var queryRolePermission = this.PermissionRepository.GetInternalRolePermissionById(
                            childrenNodeContext.CruiseControl.InternalSecurity, new Guid(treeNodeIndentity.Key));
                    var newUserNamesTreeNode = treeNodesBuilder.BuildInternalUserNamesNode(queryRolePermission, childrenNodeContext.SelectedNode);
                    childrenNodeContext.SelectedNode.Expand();
                    newUserNamesTreeNode.Expand();
                }
            }
            else
            {
                this.Successor.UpdateChildrenNodes(childrenNodeContext);
            }
        }
    }
}
